package com.coolwar.design.proxy.dynamic.mybatis;

import java.lang.reflect.Proxy;


/**
 * @author Coolwar
 * 动态代理
 */
public class ProxyFactory<T> {

    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;

    public ProxyFactory(SqlSession sqlSession, Class<T> mapperInterface) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
    }

    public T newInstance() {
        return (T) Proxy.newProxyInstance(
                mapperInterface.getClassLoader(),
                new Class[]{mapperInterface},
                (proxy, method, args) -> {
                    MapperMethod mapperMethod = new MapperMethod(mapperInterface.getName() + "." + method.getName(), method);
                    return mapperMethod.execute(sqlSession, args);
                }
        );
    }

}
